/*
 * HomePage.java
 *
 * Created on Streda, 2011, január 12, 22:51
 */
package sk.itat.wicket;

import java.util.ArrayList;
import org.apache.wicket.markup.html.form.Form;
import org.apache.wicket.markup.html.form.PasswordTextField;
import org.apache.wicket.markup.html.form.TextField;
import org.apache.wicket.markup.html.link.Link;
import org.apache.wicket.markup.html.panel.FeedbackPanel;
import org.apache.wicket.model.PropertyModel;

public class LoginPage extends BasePage {

    private String login;
    private String heslo;

    public LoginPage() {

        TextField logFld = new TextField("login", new PropertyModel(this, "login"));
        logFld.setRequired(true);
        PasswordTextField heslFld = new PasswordTextField("heslo", new PropertyModel<String>(this, "heslo"));
        heslFld.setRequired(true);
        heslFld.setResetPassword(false);

        Link lnkReg = new Link("lnkReg") {

            @Override
            public void onClick() {
                setResponsePage(new RegistrationPage());
            }
        };

        Form form = new LoginForm("loginForm");

        form.add(logFld);
        form.add(heslFld);

        FeedbackPanel feedback = new FeedbackPanel("errors");
        add(feedback);

        add(new HeaderPanel("mainNavigation", "Login"));
        add(form);
        add(lnkReg);

    }

    class LoginForm extends Form {

        public LoginForm(String id) {
            super(id);
        }

        @Override
        protected void onSubmit() {
            String meno = getLogin();
            String heslo = getHeslo();

            Uzivatel person = existujeuser(meno, heslo);
            if (person != null) {
                setResponsePage(new WelcomePage(person));

            } else {
                setResponsePage(LoginPage.class);
            }
        }
    }

    public Uzivatel existujeuser(String meno, String heslo) {

        ArrayList<Uzivatel> zoznam = (ArrayList<Uzivatel>) Application.get().getZoznam();
        for (int i = 0; i < zoznam.size(); i++) {
            if (zoznam.get(i).getLogin().equals(meno)) {
                if (zoznam.get(i).getHeslo().equals(heslo)) {
                    return zoznam.get(i);
                }
            }
        }

        return null;
    }

    public String getHeslo() {
        return heslo;
    }

    public void setHeslo(String heslo) {
        this.heslo = heslo;
    }

    public String getLogin() {
        return login;
    }

    public void setLogin(String login) {
        this.login = login;
    }
}
